package com.gzq.singleton.practice0;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 懒汉式： 静态常量、静态代码块。<br>
 * 饿汉式： 方法锁synchronized、双重校验锁、静态内部类。<br>
 * 枚举：<br>
 * 
 * 反射和序列化。<br>
 * 
 * @author Administrator
 *
 */
public class SingletonStaticCst implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String[] args)
			throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException, IOException, ClassNotFoundException {
		SingletonStaticCst singleton1 = SingletonStaticCst.getSingleton();
		SingletonStaticCst singleton2 = SingletonStaticCst.getSingleton();
		System.out.println(singleton1);
		System.out.println(singleton2);

		// 反射
		Constructor<SingletonStaticCst> constructor = SingletonStaticCst.class.getDeclaredConstructor();
		constructor.setAccessible(true);
		SingletonStaticCst newInstance = constructor.newInstance();
		System.out.println(newInstance);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(singleton1);

		byte[] byteArray = baos.toByteArray();

		InputStream inputStream = new ByteArrayInputStream(byteArray);
		ObjectInputStream ois = new ObjectInputStream(inputStream);
		Object readObject = ois.readObject();
		System.out.println(readObject);

	}

	private static SingletonStaticCst singleton;
	static {
		singleton = new SingletonStaticCst();
	}

	private SingletonStaticCst() {
	}

	public static SingletonStaticCst getSingleton() {
		return singleton;
	}

}
